package cn.xmall.intercepters;

import cn.xmall.commons.models.RequestResult;
import cn.xmall.commons.utils.CookieUtils;
import cn.xmall.models.User;
import cn.xmall.services.UserService;
import cn.xmall.services.cn.xmall.services.WeiXinUserService;
import cn.xmall.vo.ErrorPageInfoEnum;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * Created by MoTaiXian on 2017/7/19.
 */
@Component
public class LoginIntercept implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginIntercept.class);
    @Value("${LOGIN_COOKIE_NAME}")
    private String COOKIE_NAME;

    private final String ERROR_PAGE_URL="/error";

    private final String USER_LOGIN_URL="/showLogin";

    private final String WX_HEADER="WXSP_XMALL_MOBILE";

    private final String WX_TOKEN_KEY="XMALL-Token";
    @Autowired
    UserService userService;
    @Autowired
    WeiXinUserService weiXinUserService;

    public void returnError(HttpServletResponse response, String msg) throws IOException {
        RequestResult result=RequestResult.error(msg);
        String resultStr= JSON.toJSONString(result);
        OutputStream outputStream=response.getOutputStream();
        response.setHeader("content-type"," text/html;charset=UTF-8");
        outputStream.write(resultStr.getBytes("UTF-8"));
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userAgent=request.getHeader("user-agent");
        String referer=request.getHeader("referer");
        String reqAgent=request.getHeader("request-agent");

        logger.debug("referer:{}",referer);
        logger.debug("user-agent:{}",userAgent);
        logger.debug("request-agent:{}",reqAgent);

        //如果是微信端用户
        if(userAgent.equals(WX_HEADER)){
            String session_token=request.getHeader(WX_TOKEN_KEY);

            //用户没有登录则返回
            if(!StringUtils.hasText(session_token)){
                returnError(response,"user do not log in");
                return false;
            }

            //判断用户是否登录超时
            User user=weiXinUserService.getLoginedUserByToken(session_token);
            if(user==null){
                returnError(response,"user login timeout");
                return false;
            }

            return true;

        }else { //web端用户处理
            //暂不开放
            response.sendRedirect("/error?code="+ ErrorPageInfoEnum.UNSUPPORT_WEB);
            return false;

//            //判断用户是否登陆
//            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
//
//            //如果用户登陆则放行 true 执行 false不执行
//            if (token != null && !token.equals("")) {
//                User user = userService.getLoggedInUserByToken(token);
//                if (user != null)
//                    return true;
//            }
//            //如果用户没有登陆跳转到登陆页面
//            //response.sendRedirect(USER_LOGIN_URL + "?redirect=" + request.getRequestURI());
//
//            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
